/**
 * ProjectName doctor
 * FileName QiNiuUtils.java
 * PackageName com.doctor.utils
 * Date 2017年6月10日 上午9:05:35
 * Copyright (c) 2015, lyg945@163.com All Rights Reserved.
 */
package com.doctor.utils;

import java.io.ByteArrayInputStream;

import org.springframework.web.multipart.MultipartFile;

import com.google.gson.Gson;
import com.qiniu.common.QiniuException;
import com.qiniu.common.Zone;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;

public class QiNiuUtils {

	String accessKey = "6cIfcIV6BQcQqaeJsWHaq0cdyepY7DcHbN3p4QII";
	String secretKey = "zKBmxmmAgShP69xB0Q0rLNwOJzSPlJpAB-IwYMYj";
	String bucket = "dreamlu";
	String upToken = "";
	UploadManager uploadManager ;
	//默认不指定key的情况下，以文件内容的hash值作为文件名
	String key = null;
	String url = "http://onpl9tx33.bkt.clouddn.com/";
	
	public QiNiuUtils(){

		Auth auth = Auth.create(accessKey, secretKey);
		upToken = auth.uploadToken(bucket);
		
		//构造一个带指定Zone对象的配置类
		Configuration cfg = new Configuration(Zone.zone1());
		//...其他参数参考类注释
		uploadManager = new UploadManager(cfg);
	}
	
	public void upload(){
		String localFilePath = "‪‪d:\\qiaoliang\\img\\bg.jpg";
		try {
//			System.out.println(upToken);
		    Response response = uploadManager.put(localFilePath, key, upToken);
		    //解析上传成功的结果
		    DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
		    System.out.println(putRet.key);
		    System.out.println(putRet.hash);
		} catch (QiniuException ex) {
		    Response r = ex.response;
		    System.err.println(r.toString());
		    try {
		        System.err.println(r.bodyString());
		    } catch (QiniuException ex2) {
		        //ignore
		    }
		}
	}
	
	public String upload(MultipartFile file){
		try {
		    ByteArrayInputStream byteInputStream=new ByteArrayInputStream(file.getBytes());
		    Auth auth = Auth.create(accessKey, secretKey);
		    String upToken = auth.uploadToken(bucket);
		    try {
		    	key = file.getOriginalFilename();
		        Response response = uploadManager.put(byteInputStream,key,upToken,null, null);
		        //解析上传成功的结果
		        DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
		        return url+putRet.key;
		    } catch (QiniuException ex) {
		        Response r = ex.response;
		        System.err.println(r.toString());
		        try {
		            System.err.println(r.bodyString());
		        } catch (QiniuException ex2) {
		            //ignore
		        }
		    }
		} catch (Exception ex) {
		    //ignore
		}
		
		return "";
	}
	
	public static void main(String[] args) {
		QiNiuUtils  util =new QiNiuUtils();
		util.upload();
	}
}
